package com.yueshop.member.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yueshop.common.utils.HttpUtils;
import com.yueshop.member.entity.MemberLevelEntity;
import com.yueshop.member.exception.PhoneExistException;
import com.yueshop.member.exception.UsernameExistException;
import com.yueshop.member.service.MemberLevelService;
import com.yueshop.member.vo.MemberRegistVo;
import com.yueshop.member.vo.SocialUserVo;
import com.yueshop.member.vo.UserLoginVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.common.utils.Query;

import com.yueshop.member.dao.MemberDao;
import com.yueshop.member.entity.MemberEntity;
import com.yueshop.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        //进行注册
        MemberEntity memberEntity = new MemberEntity();
        //对手机号 及用户名进行校验, 校验通过再进行注册
        checkUsernameUnique(vo.getUsername());
        checkPhoneUnique(vo.getPhone());

        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setNickname(vo.getUsername());
        memberEntity.setCreateTime(new Date());
        memberEntity.setIntegration(0);
        //设置默认会员等级
        MemberLevelEntity mle = memberLevelService.getOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        memberEntity.setLevelId(mle.getId());
        //设置密码 进行加密存储.
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(vo.getPassword());
        memberEntity.setPassword(password);
        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new  UsernameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(count>0){
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        //登录方法
        //1.去数据库查询  select * from memeber where username =loginacct or mobile = loginacct
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()).or().eq("mobile", vo.getLoginacct()));

        //判断memberEntity 是否为null
        if(memberEntity==null){
            return null;
        }else{
            //去验证密码是否正确
            String password = memberEntity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

            boolean matches = encoder.matches(vo.getPassword(), password);
             if(matches){
                //如果密码正确 返回对象
                 return memberEntity;
             }else {
                return null;
             }

        }
    }

    /**
     * 微博社交登录 如果以前未登录过 需要进行注册  登录过 跟新一下 令牌及过期时间
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(SocialUserVo vo) {

        String uid = vo.getUid();
        //通过uid判断当前的社交用户是否以前登录注册过
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if(memberEntity!=null){
        //说明 以前登录注册过了
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            //更新
            baseMapper.updateById(memberEntity);
            return memberEntity;
        }else{

            MemberEntity entity = new MemberEntity();
            //说明 没有登陆过 需要注册一下
            //发送请求查询当前社交用户信息
            try {
                Map<String,String> map = new HashMap<>();

                map.put("access_token",vo.getAccess_token());
                map.put("uid",uid);
                //https://api.weibo.com/2/users/show.json?
                HttpResponse get = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);

                if(get.getStatusLine().getStatusCode()==200){
                    String json = EntityUtils.toString(get.getEntity());

                    JSONObject jsonObject = JSON.parseObject(json);
                    //获取昵称
                    String name = jsonObject.getString("name");
                    entity.setNickname(name);

                    String gender = jsonObject.getString("gender");
                    entity.setGender("m".equals(gender)?1:0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            entity.setSocialUid(vo.getUid());
            entity.setAccessToken(vo.getAccess_token());
            entity.setExpiresIn(vo.getExpires_in());
            entity.setCreateTime(new Date());
            baseMapper.insert(entity);
            return entity;
        }
    }


}